from typing import List, Dict
import sqlite3
import random
from tqdm import tqdm

letter2name = {
    "A": "马列主义",
    "B": "哲学与宗教",
    "C": "社会科学",
    "D": "政法",
    "E": "军事",
    "F": "经济",
    "G": "文体",
    "H": "语言",
    "I": "文学",
    "J": "艺术",
    "K": "史地",
    "N": "自然科学",
    "O": "数理化",
    "P": "天文",
    "Q": "生物科学",
    "R": "医药",
    "S": "农业科学",
    "T": "工学",
    "U": "交通运输",
    "V": "航空航天",
    "X": "环境与安全",
    "Z": "综合性"
}


class Interaction:
    def __init__(self, item_id, user_id, interaction_type=0, info=None, extra_info=None):
        self.item_id = item_id
        self.user_id = user_id
        self.interaction_type = interaction_type  # 0: Reader
        self.info = info
        self.extra_info = extra_info


class FileLoader:
    def __init__(self, hyper_params):
        self.filename = hyper_params['dataset_path']
        self.book = {}
        self.reader = {}
        self.id_to_book = {}
        self.intereaction_list: Dict[int, List[Interaction]] = {}
        self.book_cnt = 0
        self.reader_cnt = 0

        self.read_from_dataset_file()
        hyper_params['item_cnt'] = self.book_cnt
        hyper_params['user_cnt'] = self.reader_cnt

    def read_from_dataset_file(self):
        conn_book = sqlite3.connect('database/book_data.db')
        conn_interact = sqlite3.connect('database/interact_data.db')
        conn_user = sqlite3.connect('database/user_data.db')
        conn_shelf = sqlite3.connect('database/shelf_data.db')

        interact_set = set()

        with open(self.filename, encoding='utf-8', errors='ignore') as file_object:
            for line in tqdm(file_object.readlines()):
                words = line.split('@')
                if len(words) > 7 and not words[7].startswith('518'):
                    continue

                if '50' in words:  # only use borrow cases
                    # use ID and book name as key
                    bookKey = words[0] + '@' + words[1]
                    if bookKey not in self.book:
                        self.book[bookKey] = self.book_cnt

                        title = words[1].replace('%', '').replace("'", '')
                        author = words[2].replace('%', '').replace("'", '')
                        publisher = words[4].replace('%', '').replace("'", '')
                        year = words[5].replace('%', '').replace("'", '')
                        shortintro = f'这本书讲述了在{year}年，发生的关于{title}的一些故事。在这本书中，作者{author}通过敏锐的洞察力，深刻分析了问题的本质。'
                        cate = letter2name['Z']
                        if len(words[0]) > 0 and words[0][0] in letter2name:
                            cate = letter2name[words[0][0]]

                        cover = 'assets/img/book.jpg'

                        chapter_cnt = random.randint(10, 50)

                        self.book_cnt = self.book_cnt + 1

                    readerKey = words[7]  # use student ID as key
                    if readerKey not in self.reader:
                        self.reader[readerKey] = self.reader_cnt
                        self.reader_cnt = self.reader_cnt + 1
                    cur_book_id = self.book[bookKey]
                    cur_reader_id = self.reader[readerKey]

                    self.id_to_book[cur_book_id] = bookKey

                    if cur_reader_id not in self.intereaction_list:
                        self.intereaction_list[cur_reader_id] = []

                    self.intereaction_list[cur_reader_id].append(
                        Interaction(cur_book_id, cur_reader_id))

        print(
            f'Reader: {self.reader_cnt}, Book: {self.book_cnt}, Interact: {len(self.intereaction_list)}')


if __name__ == '__main__':
    hyper_params = {
        'dataset_path': 'BPR/datasets/lib.txt'
    }

    file_loader = FileLoader(hyper_params=hyper_params)
    print(
        f'Reader: {file_loader.reader_cnt}, Book: {file_loader.book_cnt}, Interact: {len(file_loader.intereaction_list)}')
